package com.zk.curator.demo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;

import java.util.List;

/**
 * <h3>partitionjob</h3>
 * <p>CrudExamples</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-23 20:32
 **/
public class CrudExamples {

    public static void create(CuratorFramework client, String path, byte[] payLoad) throws Exception {
        // this will create the given ZNode with the given data
        client.create().forPath(path, payLoad);
    }

    public static void createEphemeral(CuratorFramework client, String path, byte[] payLoad) throws Exception {
        client.create().withMode(CreateMode.EPHEMERAL).forPath(path, payLoad);
    }

    public static String createEphemeralSequential(CuratorFramework client, String path, byte[] payLoad) throws Exception {
        return client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, payLoad);
    }

    public static void setData(CuratorFramework client, String path, byte[] payload) throws Exception {
        client.setData().forPath(path, payload);
    }

    public static void setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception {
        CuratorListener listener = new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("返回事件： " + event.getWatchedEvent());
            }
        };
        client.getCuratorListenable().addListener(listener);
        client.setData().inBackground().forPath(path, payload);
    }

    public static void setDataAsyncWithCallback(CuratorFramework client, String path, byte[] payload, BackgroundCallback callback) throws Exception {
        client.setData().inBackground(callback).forPath(path, payload);
    }

    public static void delete(CuratorFramework client, String path) throws Exception {
        client.delete().forPath(path);
    }

    public static void guaranteeDelete(CuratorFramework client, String path) throws Exception {
        client.delete().guaranteed().forPath(path);
    }

    public static List<String> watchedGetChildren(CuratorFramework client, String path) throws Exception {
        return client.getChildren().watched().forPath(path);
    }

    public static List<String> watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception
    {
        /**
         * Get children and set the given watcher on the node.
         */
        return client.getChildren().usingWatcher(watcher).forPath(path);
    }

}
